'use strict';
var common = angular.module('common', []);

common.factory("commonService", ["i18n", function (i18n) {
  return {
    blockUI: function (target) {
      if (target !== undefined) {
        window.blockUITarget = target;
        Metronic.blockUI({
          target: target,
          boxed: true,
          message: "loading"
        });
      } else {
        Metronic.blockUI({
          boxed: true,
          message: "loading"
        });
      }
    },
    ajaxCallback: function (data) {
      Metronic.unblockUI(window.blockUITarget);
      var msg = i18n.translate(data.returnMsg);
      if (data.ok) {
        toast.success(msg);
        return true;
      } else if (data.error) {
        toast.error(msg);
        return false;
      } else if (data.warn) {
        toast.warn(msg);
        return true;
      }
    }
  }
}]);

$(function () {
  //此函数为了处理firefox及chrome中，在弹出的窗口中点击ckeditor的上传图片，显示的input无法获取光标的问题
  $.fn.modal.Constructor.prototype.enforceFocus = function () {
    var modal_this = this;
    $(document).on('focusin.modal', function (e) {
      if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
        && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select')
        && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
        modal_this.$element.focus()
      }
    })
  };
  $.ajaxSetup({
    cache: false,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.responseJSON) {
        toast.error(XMLHttpRequest.responseJSON.returnMsg);
      } else {
        toast.error("state：" + XMLHttpRequest.status + ", error：" + XMLHttpRequest.statusText)
      }
      Metronic.unblockUI(customGlobal.blockUITarget);
    }
  });
  $.validator.setDefaults({
    errorElement: 'span', //default input error message container
    errorClass: 'help-block help-block-error', // default input error message class
    focusInvalid: true,
    ignore: "",  // validate all fields including form hidden input
    highlight: function (element) { // hightlight error inputs
      $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
    },
    unhighlight: function (element) { // revert the change done by hightlight
      $(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
    },
    success: function (label) {
      label.closest('.form-group').removeClass('has-error'); // set success class to the control group
    },
    invalidHandler: function (event, validator) { //display error alert on form submit
      toastr.error("tableWrong");
    }
  });
  $.validator.messages.equalTo = "diffInput";
  var $menuSearch = $("#menuSearch").on("keydown", function (e) {
    var $this = $(this);
    var menuId = $this.getGAutoHiddenValue();
    if (e.which == 13 && menuId != undefined && menuId != "") {
      e.preventDefault();
      customGlobal.menuSearch(menuId);
    }
  });
  $("#menuSearchBtn").on("click", function () {
    var menuId = $menuSearch.getGAutoHiddenValue();
    if (menuId != undefined && menuId != "") {
      customGlobal.menuSearch(menuId)
    }
  });
  customGlobal.initUpdatePasswordEvent();
});
var customGlobal = {
  onSortColumnDefault: function (sortColumn, sortDirection) {
    return {
      sortColumn: sortColumn,
      sortDirection: sortDirection
    }
  },
  clearFormAndShowDialog: function (dialogId) {
    $("#" + dialogId).find("input:text,input:password,select,textarea").val("").end().modal("show").find("div.form-group").removeClass("has-error");
  },
  menuSearch: function (menuId) {
    $.post("develop/menu/menuSearch", {menuId: menuId}, function (data) {
      if (customGlobal.ajaxCallback(data)) {
        location.href = data.returnData.url;
      }
    })
  },
  initUpdatePasswordEvent: function () {
    $("#updatePass").on("click", function () {
      customGlobal.clearFormAndShowDialog("updatePasswordModal");
      $("#updatePasswordDialog").validate({
        rules: {
          oldPassword: {
            required: true
          },
          reNewPassword: {
            equalTo: "#newPassword"
          }
        }
      }).resetForm();
      $("#passwordHelpBlock").html("");
    });

    $("#updatePassword").on("click", function () {
      customGlobal.blockUI("#updatePasswordContent");
      $.ajax({
        url: "security/user/updatePassword",
        data: {
          oldPassword: $("#oldPassword").val().md5(),
          newPassword: $("#newPassword").val().md5()
        },
        type: "post",
        success: function (data) {
          if (customGlobal.ajaxCallback(data)) {
            $("#updatePasswordModal").modal("hide");
          }
        }
      });
    });
  },
  /**
   * 通过html导出excel
   * @param colNum excel的列数
   * @param rowNum excel标题+表头的行数
   * @param htmlObj 包含要导出数据html的jquery对象
   * @param excelVersion excel版本包括（xls,xlsx）
   */
  exportByHtml: function (colNum, rowNum, htmlObj, excelVersion) {
    colNum = colNum == undefined ? $("#colNum").val() : colNum;
    if (colNum > 254) {
      excelVersion = "xlsx"
    }
    rowNum = rowNum == undefined ? $("#rowNum").val() : rowNum;
    rowNum = rowNum == undefined ? 2 : rowNum;
    htmlObj = htmlObj == undefined ? $("#dataListDiv") : htmlObj;
    excelVersion = excelVersion == undefined ? $("#excelVersion").val() : excelVersion;
    excelVersion = excelVersion == undefined ? "xls" : excelVersion;

    var form = $("<form>").attr('style', 'display:none').attr('target', '_self').attr('method', 'post')
      .attr('action', basePath + "exportExcel/exportExcelByHtml");
    var colNumObj = $('<input>').attr('type', 'hidden').attr('name', 'colNum').val(colNum);
    var rowNumObj = $('<input>').attr('type', 'hidden').attr('name', 'tableHeadRowNum').val(rowNum);
    var htmlStrObj = $('<input>').attr('type', 'hidden').attr('name', 'htmlStr').val(htmlObj.html());
    var excelVersionObj = $('<input>').attr('type', 'hidden').attr('name', 'excelVersion').val(excelVersion);
    $('body').append(form);
    form.append(colNumObj).append(rowNumObj).append(htmlStrObj).append(excelVersionObj).submit().remove();
  },
  /**
   * 通过后台导出excel
   * @param url
   * @param data
   */
  formSubExport: function (url, data) {
    var form = $("<form>").attr('style', 'display:none').attr('target', '_self').attr('method', 'post')
      .attr('action', basePath + url);
    $('body').append(form);
    for (var i = 0; i < data.length; i++) {
      var inputStr = $('<input>').attr('type', 'hidden').attr('name', data[i].name).val(data[i].value);
      form.append(inputStr)
    }
    form.submit().remove();
  },
  generalClass: {
    0: "label-danger",
    1: "label-success"
  }
};
